package org.itboys.product.service;

import com.google.common.collect.Maps;
import org.itboys.commons.CommonConstants;
import org.itboys.mongodb.core.MongoDataSource;
import org.itboys.mongodb.service.BaseService;
import org.itboys.mongodb.utils.page.Page;
import org.itboys.pay.alipay.AlipayWapResult;
import org.itboys.pay.weixin.WXPayService;
import org.itboys.product.constant.ProductConstant;
import org.itboys.product.entity.Order;
import org.itboys.product.entity.Product;
import org.itboys.redis.RedisCacheClient;
import org.mongodb.morphia.query.Query;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * Created by huml on 2016/4/19.
 * 订单业务
 */
@Service
public class OrderService extends BaseService<Order, Long> {
    private static final long serialVersionUID = 4495340193729890410L;

    protected Logger logger = LoggerFactory.getLogger(getClass());

    @Resource(name="productDS")
    private MongoDataSource orderDS;
    @Autowired
    private ProductService productService;
    @Autowired
    private RedisCacheClient redisCacheClient;

    @Override
    protected MongoDataSource getMongoDataSource() {
        return orderDS;
    }

    @Override
    protected Class<Order> getEntityClass() {
        return Order.class;
    }

    /**
     * 立即购买创建订单
     * @param memberId  购买人id
     * @param productId  产品id
     * @param num  数量
     * @param payMethod  支付方式
     * @param address  地址
     * @param name  订单备注
     * @param mobile 手机号码
     */
    public Order createOrder(Long memberId, Long productId, Integer num,
                            Integer payMethod, String address, String name, String mobile, String postcode){
        Order order = new Order();
        order.setStatus(ProductConstant.OrderStatic.ORDER_STATUS_CREATE);
        order.setMemberId(memberId);
        order.setProductId(productId);
        order.setNum(num);
        order.setPayMethod(payMethod);
        order.setCreateTime(new Date());
        order.setUpdateTime(new Date());
        Product product = productService.getById(productId);
        order.setSellerId(product.getSellerId());
        order.setProductName(product.getName());
        order.setProductImage(product.getImage());
        if(product.getProductStore() == null || product.getProductStore() == 0){
            return null;
        }
        product.setProductStore(product.getProductStore() - num);
        productService.update(product);
        if(payMethod.equals(ProductConstant.OrderStatic.PAY_BEAN)){
            order.setTotalFee(product.getPowerBean() * 100L * num);
        } else {
            order.setTotalFee(Long.parseLong((product.getPrice()* num) + "") );
        }
        order.setMobile(mobile);
        order.setName(name);
        order.setAddress(address);
        order.setPostcode(postcode);
        super.save(order);
        return order;
    }

    /**
     * 微信支付异步回调处理
     *
     * @param request
     * @return
     * @throws Exception
     */
    @Transactional
    public String weixinNotify(HttpServletRequest request) throws Exception{
        boolean readed = true;
        try {
            AlipayWapResult wapResult = WXPayService.notifyResult(request, "1");
            String orderNo = wapResult.getOut_trade_no();
            Order order = getByField("orderNo", orderNo);
            logger.info("**********orderNo**********"+orderNo);
            if(order == null){
                logger.info("****************order == null*************");
                return CommonConstants.FAIL;
            }
           /* if(member.getReaded()){
                readed = false;
            }
            member.setReaded(true);
            WeixinConfig weixinConfig = weixinConfigService.getById(Long.valueOf(member.getWeixinId()));*/
            /*wapResult = WXPayService.checkIsSuccess(wapResult, weixinConfig.getMcKkey());
            System.out.println(wapResult.toString());
            if (!wapResult.getParams().get(PayConstants.WeixinPay.RESULT_CODE).equals(CommonConstants.SUCCESS.toUpperCase())) {//签名校验失败
                logger.info("****************sign error*************");
                return CommonConstants.FAIL;
            }*/
            /*if(wapResult.getPrice().compareTo(new BigDecimal(order.getTotalFee())) != 0){//支付金额不正确
                logger.info("****************price error*************");
                return CommonConstants.FAIL;
            }*/

            //修改订单状态
            order.setStatus(ProductConstant.OrderStatic.ORDER_STATUS_PAY);
            order.setPayMethod(ProductConstant.OrderStatic.PAY_WX);
            order.setPayTime(new Date());
            super.update(order);
            logger.info("****************success*************");
            return CommonConstants.SUCCESS;
        } catch (Exception e) {
            //mongo手动回滚
            throw new RuntimeException(e);
        }
    }


    /**
     * 订单首页
     * @param rows
     * @param status
     * @return
     */
    public List<Order> myOrderFirstPage(Integer rows, Integer status, Long memberId){
        Query<Order> query = getMongoDataSource().createQuery(getEntityClass()).filter("isDeleted",0).filter("memberId", memberId);
        if(status != null){
            if(status == 0){
                query = query.filter("status", status);
            } else {
                query = query.filter("status >", 0);
            }
        }
        query.order("-createTime").offset(0).limit(rows);
        return query.asList();
    }

    /**
     * 分页获取订单
     * @param memberId
     * @param status
     * @param request
     * @return
     */
    public List<Order> myOrder(Long memberId, Integer status, HttpServletRequest request){
        Map<String, Object> param = Maps.newHashMapWithExpectedSize(2);
        param.put("memberId", memberId);
        param.put("isDeleted", 0);
        if(status != null){
            if(status == 0){
                param.put("status", status);
            }else {
                param.put("status >", 0);
            }
        }
        Page<Order> page = pageQuery(param, request);
        return page.getData();
    }
    
}
